package com.leyou.controller;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.config.JwtProperties;
import com.leyou.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/11/5
 * Time: 20:06
 * *
 */
@Controller
@EnableConfigurationProperties(value = JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录授权
     * @param username
     * @param password
     * @param request
     * @param response
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response
            ) {

        //登录校验
        String token = this.authService.authentication(username, password);
        if (StringUtils.isBlank(token)) {
            //401（登录身份未认证）
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        //将jwt(token)存入cookie中，并指定httponly为true，防止通过js获取和修改
        CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire()*60, null, true);
        return ResponseEntity.ok().build();
    }

    /**
     * 验证用户信息（解决登录状态问题）
     *
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(
            @CookieValue(value = "LY_TOKEN", required = false) String token,
            HttpServletResponse response,
            HttpServletRequest request) {

        try {
            //从token中解析token信息
            UserInfo userinfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (userinfo == null) {
                //解析失败，返回401
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            //重新获取token
            token = JwtUtils.generateToken(userinfo, this.jwtProperties.getPrivateKey(), this.jwtProperties.getExpire());
            //更新cookie中的token
            CookieUtils.setCookie(request, response, this.jwtProperties.getCookieName(), token, this.jwtProperties.getExpire()*60, null, true);
            //解析成功，返回用户信息
            return ResponseEntity.ok(userinfo);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //解析失败，返回401
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }
}
